package org.jdsm.gae.komarichyn.blog;

import com.google.appengine.api.datastore.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * User: mikom
 * Date: 11/13/12
 * Time: 1:39 PM
 */
public class FileManagerHelper {


    private static String FOLDER = "__folder";
    private static String FILE = "__file";
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

    public void createFolder(Folder folder) {
        Key k = KeyFactory.createKey(Folder.class.getSimpleName(), System.currentTimeMillis());
        Entity folderEntity = new Entity(FOLDER, k);
        folderEntity.setProperty("title", folder.getTitle());
        folderEntity.setProperty("key", KeyFactory.keyToString(k));

        datastore.put(folderEntity);
    }

    public void createFile(File file, Folder parent, ByteArrayOutputStream byteArrayOutputStream) throws IOException, EntityNotFoundException {

        Entity folder;
        Key k;
        if (parent != null) {
            folder = datastore.get(KeyFactory.stringToKey(parent.getKey()));
            k = KeyFactory.createKey(folder.getKey(), File.class.getSimpleName(), System.currentTimeMillis());
        } else {
            k = KeyFactory.createKey(File.class.getSimpleName(), System.currentTimeMillis());
        }

        Entity fileEntity = new Entity(FILE, k);
        fileEntity.setProperty("name", file.getName());
        fileEntity.setProperty("date", file.getDate());
        fileEntity.setProperty("ext", file.getExt());
        fileEntity.setProperty("height", file.getHeight());
        fileEntity.setProperty("width", file.getWidth());
        fileEntity.setProperty("mtime", file.getMtime());
        fileEntity.setProperty("r_size", file.getR_size());
        fileEntity.setProperty("size", file.getSize());
        fileEntity.setProperty("thumb", file.getThumb());
        fileEntity.setProperty("key", KeyFactory.keyToString(k));

        k = persistData(k, byteArrayOutputStream.toByteArray());
        fileEntity.setProperty("biteDataKey", KeyFactory.keyToString(k));

        datastore.put(fileEntity);
    }

    public List<File>  getFiles() {
        List<File> files = new ArrayList<File>();
        Query q = new Query(FILE);
        PreparedQuery pq = datastore.prepare(q);
        for (Entity result : pq.asIterable()) {
            File file = new File();
            file.setName((String) result.getProperty("name"));
            file.setHeight((Long) result.getProperty("height"));
            file.setWidth((Long) result.getProperty("width"));
            file.setR_size((Long) result.getProperty("r_size"));
            file.setSize((String) result.getProperty("size"));

            file.setDate((Date) result.getProperty("date"));
            file.setMtime((Long) result.getProperty("mtime"));
            file.setExt((String) result.getProperty("ext"));
            file.setKey((String) result.getProperty("key"));
            files.add(file);
//            file.setThumb((String) result.getProperty("thumb"));
            file.setThumb("/fileManager/view?fileKey="+(String)result.getProperty("biteDataKey"));
        }
        return files;
    }

    private Key persistData(Key parentKey, byte[] buffer) {
        Entity data = new Entity("byteData", System.currentTimeMillis());
        Blob d = new Blob(buffer);
        data.setProperty("data", d);
        Key k = KeyFactory.createKey(parentKey, Byte.class.getSimpleName(), System.currentTimeMillis());
        data.setProperty("key", KeyFactory.keyToString(k));
        Key resultKey = datastore.put(data);
        return resultKey;
    }

    public void buildKey() throws IOException {
        for (int i = 0; i < 3; i++) {
            Key k = KeyFactory.createKey(DirMode.class.getSimpleName(), System.currentTimeMillis());
            System.out.println(KeyFactory.keyToString(k));
        }


    }


    public byte[] findByKey(String fileKey) {
        try {
            Entity data = datastore.get(KeyFactory.stringToKey(fileKey));
            Blob b = (Blob) data.getProperty("data");
            return b.getBytes();
        } catch (EntityNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}
